package com.bite.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bit.common.security.handler.ServiceException;
import com.bite.api.RemoteJudgeService;
import com.bite.api.domain.UserExeResult;
import com.bite.api.domain.dto.JudgeSubmitDTO;
import com.bite.api.domain.vo.UserQuestionResultVO;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ProgramType;
import com.bite.common.core.enums.QuestionResType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.friend.domain.question.Question;
import com.bite.friend.domain.question.QuestionCase;
import com.bite.friend.domain.question.es.QuestionES;
import com.bite.friend.domain.user.UserSubmit;
import com.bite.friend.domain.user.dto.UserSubmitDTO;
import com.bite.friend.elasticsearch.QuestionRepository;
import com.bite.friend.mapper.question.QuestionMapper;
import com.bite.friend.mapper.user.UserSubmitMapper;
import com.bite.friend.rabbit.JudgeProducer;
import com.bite.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class IUserQuestionServiceImpl implements IUserQuestionService {


    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;


    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {

        //先判断语言类型
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)){
            //按照java逻辑执行
            //创建dto
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);

            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
        //根据questionId从es查数据,拼接
        //main,用例,时间,空间,难易程度  传给judge

    }

    /**
     * rabbit方式
     * @param submitDTO
     * @return
     */
    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        //先判断语言类型
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)){
            //按照java逻辑执行
            //创建dto
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);

            //return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
            //dto传给rabbitmq
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    /**
     * 从表中查数据
     * @param questionId
     * @param examId
     * @param currentTime
     * @return
     */
    @Override
    public UserQuestionResultVO exeResult(Long examId,Long questionId,  String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId,examId,questionId,currentTime);
        UserQuestionResultVO resultVO = new UserQuestionResultVO();
        if (userSubmit == null){
            //判题还没结束
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }else {
            //赋值
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            //给前端返回的数据要转为对象
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return resultVO;
    }


    //创建dto
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {

        //从根据questionid从es查main,用例,时间,空间,难易程度....
        Long questionId = submitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null){
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else {
            //查数据库
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            //es同步
            questionES  = new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        //拼接
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFuc()));
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);

        //通过流处理,分成两个list
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outPutList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outPutList);
        return judgeSubmitDTO;
    }


    //拼接main函数和代码
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }


}
